package pers.cz.postgirl.util;

import com.alibaba.fastjson.JSON;
import pers.cz.postgirl.core.Spy;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 该队列用于保存全局ThreadLocal
 * @program: MyQueue
 * @description:
 * @author: Cheng Zhi
 * @create: 2022-02-18 15:18
 **/
public class ContextUtils {

    private static JefLog log = new JefLog(ContextUtils.class);
    public static final ThreadLocal<String> contextCaseId = new ThreadLocal<String>();
    public static final ThreadLocal<Map<String, Boolean>> methodContext = new ThreadLocal<Map<String, Boolean>>();

    /**
     * 方法栈，只存储当前线程的入参，当匹配到出参时会被移出。
     */
    private static final ThreadLocal<Stack<Spy>> methodStack = new ThreadLocal<Stack<Spy>>();

    /**
     * 入栈
     * @param spy
     */
    public static void pushMethodStack(Spy spy) {
        Stack<Spy> spies = methodStack.get();
        if (spies == null || spies.isEmpty()) {
            spies = new Stack<Spy>();
            methodStack.set(spies);
        }
        methodStack.get().push(spy);
    }

    /**
     * 出栈
     * @return
     */
    public static Spy popMethodStack() {

        Stack<Spy> spies = methodStack.get();

        return spies == null && spies.size() >0 ? null : spies.pop();
    }

    /**
     * 删除指定key
     * @param key
     */
    public static void remove(String key) {
        methodContext.get().remove(key);
    }

    public static void putEle(String key, Boolean value) {

        if (methodContext.get() != null) {
            methodContext.remove();
        }
        Map<String, Boolean> map = new HashMap<>();
        methodContext.set(map);
        methodContext.get().put(key, value);
    }

    public static Boolean getEle(String key) {
        Map<String, Boolean> stringBooleanMap = methodContext.get();
        Boolean aBoolean = stringBooleanMap == null? null : stringBooleanMap.get(key);
        if (aBoolean == null) {
            return false;
        }
        return aBoolean;
    }

    public static void putCaseId(String caseId) {
        contextCaseId.set(caseId);
    }

    public static String getCaseId() {
        return contextCaseId.get();
    }

    public static void remoteAll() {
        contextCaseId.remove();
        methodContext.remove();
    }
}
